#!/bin/sh

. /lib/functions.sh
. /etc/diag.sh

case "$ACTION" in
pressed)
	return 5
;;
timeout)
	. /etc/diag.sh
	set_state failsafe
;;
released)
	get_status_led
	if [ "$SEEN" -lt 1 ]
	then
		type hostapd_cli || exit

		cd /var/run/hostapd
		for socket in *; do
			[ -S "$socket" ] || continue
			[ "$(hostapd_cli -i "$socket" wps_pbc)" = "OK" ] && {
				WPS_LED=$(ls /sys/class/leds | grep -E 'qss|wps' | head -n 1)
				[ -z "$WPS_LED" ] || {
					led_timer $WPS_LED 300 300
					hostapd_cli -i "$socket" -P /var/run/hostapd-cli-wpsled-$socket.pid -a /lib/hostapd_wps_led.sh -B
				}
			}
		done

	elif [ "$SEEN" -le 5 ] && [ "$SEEN" -ge 2 ]
	then
		echo "Unmount Hard Disks" > /dev/console
		led_timer $status_led 300 300
		[ -f /etc/init.d/xunlei ] && /etc/init.d/xunlei stop
		[ -f /etc/init.d/aria2 ] && /etc/init.d/aria2 stop
		[ -f /etc/init.d/transmission ] && /etc/init.d/transmission stop
		[ -f /etc/init.d/samba ] && /etc/init.d/samba stop
		[ -f /etc/init.d/vsftpd ] && /etc/init.d/vsftpd stop
		umount /dev/sd*
		logger -t Auto-Mount "Button action: Unmount Hard Disks"
		[ -f /etc/init.d/samba ] && /etc/init.d/samba start
		[ -f /etc/init.d/vsftpd ] && /etc/init.d/vsftpd start
		sleep 1
		status_led_on
	elif [ "$SEEN" -gt 5 ]
	then
		echo "FACTORY RESET" > /dev/console
		status_led_blink_failsafe
		jffs2reset -y && reboot &
	fi
;;
esac

return 0
